package p.ithorns.framework.logger;

import ch.qos.logback.classic.Level;
import ch.qos.logback.classic.Logger;
import ch.qos.logback.classic.LoggerContext;
import org.slf4j.LoggerFactory;

import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * LogbackHelper
 *
 * @author Ht.L
 * @date 2024-03-11 13:45
 * @since 1.0.0
 */
public class LogbackHelper {

    /**
     * 获取日志列表
     */
    public static List<Map<String, String>> getLoggers() {
        // 获取到 LoggerContext
        LoggerContext loggerContext = (LoggerContext) LoggerFactory.getILoggerFactory();

        // 获取系统中定义的所有 ithorns-boot-starter-logger
        List<Map<String, String>> loggers = loggerContext.getLoggerList().stream().map(logger -> {
            // 映射为 Map，key 是 ithorns-boot-starter-logger 名称，value 是其日志级别
            // logger名称 = logger有效级别
            return Collections.singletonMap(logger.getName(), logger.getEffectiveLevel().levelStr);
        }).collect(Collectors.toList());

        return loggers;
    }

    /**
     * 设置日志级别
     */
    public static void setLevel(String name, int level) {
        // logback的LoggerContext
        LoggerContext loggerContext = (LoggerContext) LoggerFactory.getILoggerFactory();
        // 获取到 LoggerContext

        // 根据指定的名称获取 ithorns-boot-starter-logger
        Logger logger = loggerContext.exists(name);
        if (logger == null) {
            System.out.println("日志记录器不存在");
            return;
        }

        // 解析 level 参数，第二个参数表示当 level 参数非法时的默认值
        Level newLevel = Level.toLevel(level, null);
        if (newLevel == null) {
            System.out.println("不是合法的日志级别");
            return;
        }

        // 重写设置 ithorns-boot-starter-logger 的 level
        logger.setLevel(newLevel);
    }

}